﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MobiShop.Models;
using System.Data;
using System.IO;

namespace MobiShop.Controllers
{
    [MyAuthorize(MyRole = 2)]
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        MobishopEntities db = new MobishopEntities();
        int productPerPage = 5;
        int accountPerPage = 7;

        #region Ham dung chung
        private void SetReturnURL(string ReturnURL)
        {
            if (ReturnURL == "") ReturnURL = null;
            if (ReturnURL == null && Request.UrlReferrer != null)
                ReturnURL = Request.UrlReferrer.AbsoluteUri;
            ViewBag.ReturnURL = ReturnURL;
        }

        private ActionResult ReturnView(string ReturnURL, string defaultAction)
        {
            if (ReturnURL == null || ReturnURL == "")
                return RedirectToAction(defaultAction);
            else return Redirect(ReturnURL);
        }

        public ActionResult Index()
        {
            return RedirectToAction("productList");
        }
        #endregion

        #region product handle
        public ActionResult productList(FindProductData find, int id = 1)
        {
            if (id <= 0) return HttpNotFound(); // ko xử lý khi yêu cầu trang ko hợp lệ

            ViewBag.CurrentLink = Request.Url.AbsoluteUri;
            ViewBag.listManufacture = new SelectList(ManufactureModels.getManufactureList(), "id", "name");
            ViewBag.listCategory = new SelectList(CategoryModels.CatMenu(), "id", "name");
            ViewBag.listRegion = new SelectList(RegionModels.GetList(), "id", "name");
            ViewBag.VisibleListItem = AppSetting.Make_Clone(AppSetting.VisibleListItem, null);

            if (!ModelState.IsValid) return View(find);

            // ra lệnh tìm kiếm
            var list = find.Find(db);
            int SoKetQua = list.Count();
            int p = SoKetQua / productPerPage;
            if (SoKetQua % productPerPage != 0)
            {
                p = p + 1;
            }

            ViewBag.SoKetQua = SoKetQua;
            ViewBag.ResultList = list.OrderBy(s => s.id).Skip((id - 1) * productPerPage).Take(productPerPage).ToList();
            ViewBag._tongSoTrang = p;
            ViewBag._trangHienTai = id;
            ViewBag._MyURL = "/Admin/productList/";
            ViewBag._Query = Request.Url.Query;
            ViewBag._UseIdForPaging = true;

            return View(find);
        }
        public ActionResult productCreate()
        {
            SetReturnURL(null);
            ViewBag.CategoryId = new SelectList(db.CategoryList, "id", "name");
            ViewBag.ManufactureId = new SelectList(db.ManufactureList, "id", "name");
            ViewBag.RegionId = new SelectList(db.RegionList, "id", "name");

            Product p = new Product();
            p.createDate = DateTime.Now;
            return View(p);
        }

        private void SaveImage(Product ap, HttpPostedFileBase image)
        {
            string fileName;
            if (image != null && image.ContentLength > 0)
            {
                fileName = Path.GetFileNameWithoutExtension(image.FileName);
                string fileExtension = Path.GetExtension(image.FileName);
                string fullPath = Path.Combine(Server.MapPath("~/Content/images/"), fileName + fileExtension);
                Random r = new Random();
                try
                {
                    while (System.IO.File.Exists(fullPath))
                    {
                        fullPath = Path.Combine(Server.MapPath("~/Content/images/"), fileName + "_" + r.Next() + fileExtension);
                    }
                    image.SaveAs(fullPath); 
                    fileName = Path.GetFileName(fullPath);
                }
                catch (Exception)
                {
                    fileName = AppSetting.DefaultImage;
                }
            }
            else fileName = AppSetting.DefaultImage;

            ap.image = fileName;
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult productCreate(Product ap, HttpPostedFileBase image, string ReturnURL)
        {
            SetReturnURL(ReturnURL);
            ap.totalSale = 0;
            ap.totalView = 0;
            
            if (ModelState.IsValid)
            {
                SaveImage(ap, image);

                db.ProductList.AddObject(ap);
                db.SaveChanges();
                return ReturnView(ReturnURL, "productList");
            }

            ViewBag.ThongBao = "Thêm thất bại!";
            ViewBag.CategoryId = new SelectList(db.CategoryList, "id", "name");
            ViewBag.ManufactureId = new SelectList(db.ManufactureList, "id", "name");
            ViewBag.RegionId = new SelectList(db.RegionList, "id", "name");
            return View(ap);
        }
        public ActionResult productEdit(int id)
        {
            SetReturnURL(null);
            Product pro = db.ProductList.Single(c => c.id == id);

            ViewBag.CategoryId = new SelectList(db.CategoryList, "id", "name", pro.categoryId);
            ViewBag.ManufactureId = new SelectList(db.ManufactureList, "id", "name", pro.manufactureId);
            ViewBag.RegionId = new SelectList(db.RegionList, "id", "name", pro.regionId);
            
            ViewBag.imgName = pro.image;
            return View(pro);
        }
        [HttpPost, ValidateInput(false)]
        public ActionResult productEdit(Product ap, HttpPostedFileBase image, bool? DeleteOldImage, string ReturnURL)
        {
            SetReturnURL(ReturnURL);
            if (ModelState.IsValid)
            {
                Product sp = ProductModels.GetAllProductById(ap.id);
                if (image != null && image.ContentLength > 0)
                {
                    SaveImage(ap, image);
                    if (DeleteOldImage != null && (bool)DeleteOldImage)
                    {
                        if (sp.image != null && sp.image != AppSetting.DefaultImage && sp.image != ap.image)
                        {
                            if (ap.image == AppSetting.DefaultImage) // thao tác update file ảnh mới thất bại
                            {
                                ap.image = sp.image; // ko xóa mà giữ nguyên ảnh cũ
                            }
                            else
                            {
                                try
                                {
                                    System.IO.File.Delete(Path.Combine(Server.MapPath("~/Content/images/"), sp.image));
                                }
                                catch (System.Exception) { }
                            }
                        }
                    }
                }
                else ap.image = sp.image;

                db.ProductList.Attach(ap);
                db.ObjectStateManager.ChangeObjectState(ap, EntityState.Modified);
                db.SaveChanges();
                return ReturnView(ReturnURL, "productList");
            }
            ViewBag.CategoryId = new SelectList(db.CategoryList, "id", "name");
            ViewBag.ManufactureId = new SelectList(db.ManufactureList, "id", "name");
            ViewBag.RegionId = new SelectList(db.RegionList, "id", "name");
            ViewBag.imgName = ap.image;
            return View(ap);
        }
        public ActionResult productDelete(int id)
        {
            SetReturnURL(null);
            Product pro = db.ProductList.Single(c => c.id == id);
            return View(pro);
        }
        [HttpPost, ActionName("productDelete")]
        public ActionResult productDeleteConfirmed(int id, string ReturnURL)
        {
            Product pro = db.ProductList.Single(c => c.id == id);
            pro.visible = false;

            db.ProductList.ApplyCurrentValues(pro);
            db.SaveChanges();
            return ReturnView(ReturnURL, "productList");
        }
        #endregion

        #region category handle
        public ViewResult categoryList(string find, bool? visible, int id = 1)
        {
            ViewBag.VisibleListItem = AppSetting.Make_Clone(AppSetting.VisibleListItem, visible.ToString().ToLower());
            ViewBag.find = find;
            ViewBag.CurrentLink = Request.Url.AbsoluteUri;

            var ds = from s in db.CategoryList
                     select s;
            if (find != null && find.Length > 0) ds = ds.Where(c => c.name.Contains(find));
            if (visible != null)
                if (visible == true) ds = ds.Where(c => c.visible == true);
                else ds = ds.Where(c => c.visible == false || c.visible == null);
            List<Category> categories = ds.ToList();
            ViewBag.SoKetQua = categories.Count;

            return View(categories);
        }
        public ActionResult categoryCreate()
        {
            SetReturnURL(null);
            return View();
        }
        [HttpPost]
        public ActionResult categoryCreate(Category ac, string ReturnURL)
        {
            SetReturnURL(ReturnURL);
            if (!ModelState.IsValid)
            {
                ViewBag.ThongBao = "Thông tin đăng ký không hợp lệ !";
                return View();
            }
            try // bắt thêm ngoại lệ
            {
                db.CategoryList.AddObject(ac);
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                ViewBag.ThongBao = "Lỗi ghi CSDL. Thông báo lỗi:" + ex.Message;
                return View();
            }

            return ReturnView(ReturnURL, "categoryList");
        }
        public ActionResult categoryEdit(int id)
        {
            SetReturnURL(null);
            Category cat = db.CategoryList.Single(c => c.id == id);
            return View(cat);
        }
        [HttpPost]
        public ActionResult categoryEdit(Category ac, string ReturnURL)
        {
            if (ModelState.IsValid)
            {
                db.CategoryList.Attach(ac);
                db.ObjectStateManager.ChangeObjectState(ac, EntityState.Modified);
                db.SaveChanges();

                return ReturnView(ReturnURL, "categoryList");
            }
            SetReturnURL(ReturnURL);
            return View(ac);
        }

        public ActionResult categoryDelete(int id)
        {
            SetReturnURL(null);
            Category cat = db.CategoryList.Single(c => c.id == id);
            return View(cat);
        }

        [HttpPost, ActionName("categoryDelete")]
        public ActionResult categoryDeleteConfirmed(int id, string ReturnURL)
        {
            Category cat = db.CategoryList.Single(c => c.id == id);
            cat.visible = false;
            db.SaveChanges();
            return ReturnView(ReturnURL, "categoryList");
        }
        #endregion

        #region manufacrure handle
        public ViewResult manufacrureList(string find, bool? visible, int id = 1)
        {
            ViewBag.VisibleListItem = AppSetting.Make_Clone(AppSetting.VisibleListItem, visible.ToString().ToLower());
            ViewBag.find = find;
            ViewBag.CurrentLink = Request.Url.AbsoluteUri;

            var ds = from s in db.ManufactureList
                     select s;
            if (find != null && find.Length > 0) ds = ds.Where(c => c.name.Contains(find));
            if (visible != null)
                if (visible == true) ds = ds.Where(c => c.visible == true);
                else ds = ds.Where(c => c.visible == false || c.visible == null);
            List<Manufacture> manufactures = ds.ToList();
            ViewBag.SoKetQua = manufactures.Count;

            return View(manufactures);
        }
        public ActionResult manufacrureCreate()
        {
            SetReturnURL(null);
            return View();
        }
        [HttpPost]
        public ActionResult manufacrureCreate(Manufacture am, string ReturnURL)
        {
            SetReturnURL(ReturnURL);
            if (!ModelState.IsValid)
            {
                ViewBag.ThongBao = "Thông tin đăng ký không hợp lệ !";
                return View();
            }

            db.ManufactureList.AddObject(am);
            db.SaveChanges();

            return ReturnView(ReturnURL, "manufacrureList");
        }
        public ActionResult manufacrureEdit(int id)
        {
            SetReturnURL(null);
            Manufacture man = db.ManufactureList.Single(c => c.id == id);
            return View(man);
        }
        [HttpPost]
        public ActionResult manufacrureEdit(Manufacture am, string ReturnURL)
        {
            if (ModelState.IsValid)
            {
                db.ManufactureList.Attach(am);
                db.ObjectStateManager.ChangeObjectState(am, EntityState.Modified);
                db.SaveChanges();
                return ReturnView(ReturnURL, "manufacrureList");
            }
            SetReturnURL(ReturnURL);
            return View(am);
        }
        public ActionResult manufacrureDelete(int id)
        {
            SetReturnURL(null);
            Manufacture man = db.ManufactureList.Single(c => c.id == id);
            return View(man);
        }
        [HttpPost, ActionName("manufacrureDelete")]
        public ActionResult manufacrureDeleteConfirmed(int id, string ReturnURL)
        {
            Manufacture man = db.ManufactureList.Single(c => c.id == id);
            man.visible = false;
            db.SaveChanges();
            return ReturnView(ReturnURL, "manufacrureList");
        }
        #endregion

        #region account handle
        public ActionResult accountList(FindAccountData find, int id = 1)
        {
            if (id <= 0) return HttpNotFound(); // ko xử lý khi yêu cầu trang ko hợp lệ

            ViewBag.CurrentLink = Request.Url.AbsoluteUri;
            ViewBag.VisibleListItem = AppSetting.Make_Clone(AppSetting.VisibleListItem, null);
            ViewBag.RoleListItem = AppSetting.GeneralRoleListItem();

            if (!ModelState.IsValid) return View(find);

            // ra lệnh tìm kiếm
            var list = find.Find(db);
            int SoKetQua = list.Count();
            int p = SoKetQua / accountPerPage;
            if (SoKetQua % accountPerPage != 0)
            {
                p = p + 1;
            }

            ViewBag.SoKetQua = SoKetQua;
            ViewBag.ResultList = list.OrderBy(s => s.id).Skip((id - 1) * accountPerPage).Take(accountPerPage).ToList();
            ViewBag._tongSoTrang = p;
            ViewBag._trangHienTai = id;
            ViewBag._MyURL = "/Admin/accountList/";
            ViewBag._Query = Request.Url.Query;
            ViewBag._UseIdForPaging = true;

            return View(find);
        }
        public ActionResult accountCreate()
        {
            SetReturnURL(null);
            return View();
        }
        [HttpPost]
        public ActionResult accountCreate(Account aa, string ReturnURL)
        {
            SetReturnURL(ReturnURL);
            if (!ModelState.IsValid)
            {
                ViewBag.ThongBao = "Thông tin đăng ký không hợp lệ !";
                return View();
            }
            aa.password = AccountModels.GetMd5(aa.password);
            db.AccountList.AddObject(aa);
            
            db.SaveChanges();
            return ReturnView(ReturnURL, "accountList");
        }
        public ActionResult accountEdit(int id)
        {
            SetReturnURL(null);
            Account acc = db.AccountList.Single(c => c.id == id);
            return View(acc);
        }
        [HttpPost]
        public ActionResult accountEdit(Account aa, string ReturnURL)
        {
            SetReturnURL(ReturnURL);
            if(ModelState.IsValid)
            {
                db.AccountList.Attach(aa);
                db.ObjectStateManager.ChangeObjectState(aa, EntityState.Modified);
                db.SaveChanges();
                return ReturnView(ReturnURL, "accountList");
            }
            return View(aa);
        }
        public ActionResult accountDelete(int id)
        {
            SetReturnURL(null);
            Account acc = db.AccountList.Single(c => c.id == id);
            return View(acc);
        }

        [HttpPost, ActionName("accountDelete")]
        public ActionResult accountDeleteConfirmed(int id, string ReturnURL)
        {
            Account acc = db.AccountList.Single(c => c.id == id);
            acc.visible = false;

            db.AccountList.ApplyCurrentValues(acc);
            db.SaveChanges();
            return ReturnView(ReturnURL, "accountList");
        }

        public ActionResult accountDetails(int id)
        {
            var query = db.AccountList.Where(account => account.id == id);
            if (query.Count() != 1) return HttpNotFound();

            return View(query.First());
        }
        
        #endregion
    }
}
